<?php
declare(strict_types = 1);
namespace app\common\lib\sms;

use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use think\facade\Log;

class AliSms implements SmsBase
{
    /**
     * @param string $phone
     * @param int $code
     * @return bool
     */

    public static function sendCode(string $phone, int $code): bool
    {
        if (empty($phone) || empty($code)) {
            return false;
        }
        try {
            AlibabaCloud::accessKeyClient(config('aliyun.sms_access_key_id'), config('aliyun.sms_access_key_secret'))
                ->regionId(config('aliyun.sms_region_id'))
                ->asDefaultClient();
        } catch (ClientException $e) {
            Log::error($e->getErrorMessage());
            return false;
        }

        $templateparam = [
            'code' => $code,
        ];
        try {
            $result = AlibabaCloud::rpc()
                ->product('Dysmsapi')
                // ->scheme('https') // https | http
                ->version('2017-05-25')
                ->action('SendSms')
                ->method('POST')
                ->host(config('aliyun.sms_host'))
                ->options([
                    'query' => [
                        'RegionId' => config('aliyun.sms_region_id'),
                        'PhoneNumbers' => $phone,
                        'SignName' => config('aliyun.sms_sign_name'),
                        'TemplateCode' => config('aliyun.sms_template_code'),
                        'TemplateParam' => json_encode($templateparam),
                    ],
                ])
                ->request();
            $resultArr = $result->toArray();
            Log::info("alisms-send-{$phone}-result:".json_encode($resultArr));
        } catch (ClientException $e) {
            Log::error($e->getErrorMessage());
            return false;
        } catch (ServerException $e) {
            Log::error($e->getErrorMessage());
            return false;
        }
        if(isset($result['Code']) && $result['Code'] == "OK") {
            return true;
        }
        return false;
    }
}